<template>
  <div class="paper-management">
    <el-card class="paper-card">
      <template #header>
        <div class="card-header">
          <span>试卷管理</span>
          <el-button type="primary" @click="showCreatePaperDialog = true">创建试卷</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <div class="search-form-content">
          <el-form-item label="试卷名称">
            <el-input v-model="searchForm.name" placeholder="请输入试卷名称" clearable />
          </el-form-item>
          <div class="search-buttons">
            <el-button type="primary" @click="searchPapers">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-form>
      
      <!-- 试卷列表 -->
      <el-table :data="paperList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="试卷名称" width="300" />
        <el-table-column prop="totalDuration" label="总时长(分钟)" width="120" />
        <el-table-column prop="totalQuestions" label="总题数" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <div class="button-group">
              <el-button size="small" type="primary" @click="editPaper(scope.row)">编辑试卷</el-button>
              <el-button size="small" type="success" @click="showImportAnswersDialog(scope.row)">导入答案</el-button>
              <el-button size="small" type="warning" @click="showPaperScoreDialog(scope.row)">分值配置</el-button>
              <el-button size="small" type="danger" @click="deletePaper(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 导入答案对话框 -->
    <el-dialog v-model="showImportAnswersDialogVisible" title="导入答案" width="800px">
      <el-form :model="importAnswersForm" label-width="100px">
        <el-form-item label="答案内容">
          <el-input
            v-model="importAnswersForm.content"
            type="textarea"
            :rows="15"
            placeholder="请粘贴答案内容，格式如下：&#10;一、政治理论（1--20）&#10;&#10;1-5: DDCCA&#10;&#10;6-10: CADBB&#10;&#10;..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportAnswersDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportAnswers">导入</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 试卷分值配置对话框 -->
    <el-dialog v-model="showPaperScoreDialogVisible" title="试卷分值配置" width="800px">
      <el-form :model="paperScoreForm" label-width="120px">
        <el-form-item label="选择试卷分值">
          <el-select 
            v-model="paperScoreForm.paperScoreId" 
            placeholder="请选择试卷分值配置" 
            clearable
            @change="onPaperScoreChange"
          >
            <el-option
              v-for="score in paperScoreList"
              :key="score.id"
              :label="`${score.examName} (${score.subject})`"
              :value="score.id"
            />
          </el-select>
          <el-button 
            type="primary" 
            link 
            @click="loadPaperScoreList" 
            :loading="paperScoreListLoading"
            style="margin-left: 10px;"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-form-item>
        
        <!-- 试卷分值详细信息 -->
        <div v-if="selectedPaperScore" class="paper-score-details">
          <el-divider />
          <div class="detail-item">
            <span class="label">考试名称:</span>
            <span class="value">{{ selectedPaperScore.examName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">科目:</span>
            <span class="value">{{ selectedPaperScore.subject }}</span>
          </div>
          <div class="detail-item">
            <span class="label">总题量:</span>
            <span class="value">{{ selectedPaperScore.totalQuestions }}</span>
          </div>
          <div class="detail-item">
            <span class="label">总分值:</span>
            <span class="value">{{ selectedPaperScore.totalScore }}</span>
          </div>
          <div class="detail-item">
            <span class="label">总时长:</span>
            <span class="value">{{ selectedPaperScore.totalTime }} 分钟</span>
          </div>
          <div v-if="selectedPaperScore.details && selectedPaperScore.details.length > 0" class="detail-section">
            <div class="section-title">各模块分值详情:</div>
            <el-table :data="selectedPaperScore.details" border stripe style="width: 100%; margin-top: 10px;">
              <el-table-column prop="part" label="部分" width="120" />
              <el-table-column prop="module" label="题型模块" width="150" />
              <el-table-column prop="questionCount" label="题量" width="80" />
              <el-table-column prop="scorePerQuestion" label="分值(每题)" width="120" />
              <el-table-column prop="totalScore" label="总分数" width="100" />
              <el-table-column prop="referenceTime" label="参考时间(分钟)" width="130" />
            </el-table>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPaperScoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleApplyPaperScore" :disabled="!paperScoreForm.paperScoreId">应用分值</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 创建/编辑试卷对话框 -->
    <el-dialog v-model="showCreatePaperDialog" :title="editingPaper ? '编辑试卷' : '创建试卷'" width="600px">
      <el-form :model="paperForm" :rules="paperRules" ref="paperFormRef" label-width="100px">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="paperForm.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="总时长" prop="totalDuration">
          <el-input-number v-model="paperForm.totalDuration" :min="1" :max="300" placeholder="请输入总时长(分钟)" />
          <span class="unit">分钟</span>
        </el-form-item>
        <el-form-item label="总题数" prop="totalQuestions">
          <el-input-number v-model="paperForm.totalQuestions" :min="1" :max="500" placeholder="请输入总题数" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreatePaperDialog = false">取消</el-button>
          <el-button type="primary" @click="savePaper">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 手动批量导入对话框 -->
    <el-dialog v-model="showManualImportDialog" title="手动批量导入题目" width="800px">
      <el-form :model="manualImportForm" label-width="100px">
        <el-form-item label="题目内容">
          <el-input
            v-model="manualImportForm.content"
            type="textarea"
            :rows="10"
            placeholder="请粘贴题目内容，格式如下：&#10;1．题目内容&#10;&#10;选项：&#10;A. 选项A&#10;B. 选项B&#10;C. 选项C&#10;D. 选项D&#10;&#10;正确答案：A&#10;解析：解析内容"
            @input="validateQuestionsRealTime"
          />
        </el-form-item>
      </el-form>
      
      <div class="manual-import-actions">
        <el-button @click="resetManualImport">重置</el-button>
      </div>
      
      <!-- 验证结果展示 -->
      <div v-if="validationResult.show" class="validation-result" :class="validationResult.type">
        <h4>{{ validationResult.title }}</h4>
        <p>{{ validationResult.message }}</p>
        <div v-if="validationResult.details && validationResult.details.length > 0">
          <h5>详细信息：</h5>
          <ul>
            <li v-for="(detail, index) in validationResult.details" :key="index">
              {{ detail }}
            </li>
          </ul>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showManualImportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleManualImport" :disabled="!validationResult.valid">导入</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 导入答案对话框 -->
    <el-dialog v-model="showImportAnswersDialogVisible" title="导入答案" width="800px">
      <el-form :model="importAnswersForm" label-width="100px">
        <el-form-item label="答案内容">
          <el-input
            v-model="importAnswersForm.content"
            type="textarea"
            :rows="15"
            placeholder="请粘贴答案内容，格式如下：&#10;一、政治理论（1--20）&#10;&#10;1-5: DDCCA&#10;&#10;6-10: CADBB&#10;&#10;..."
            @input="validateAnswersRealTime"
          />
        </el-form-item>
      </el-form>
      
      <!-- 验证结果展示 -->
      <div v-if="answerValidationResult.show" class="validation-result" :class="answerValidationResult.type">
        <h4>{{ answerValidationResult.title }}</h4>
        <p>{{ answerValidationResult.message }}</p>
        <div v-if="answerValidationResult.details && answerValidationResult.details.length > 0">
          <h5>详细信息：</h5>
          <ul>
            <li v-for="(detail, index) in answerValidationResult.details" :key="index">
              {{ detail }}
            </li>
          </ul>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportAnswersDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImportAnswers" :disabled="!answerValidationResult.valid">导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PaperQuestionManager from '@/components/PaperQuestionManager.vue'
import * as paperApi from '@/api/paper'
import * as paperScoreApi from '@/api/paperScore' // 添加试卷分值API导入
import * as politicsApi from '@/api/politics'
import * as commonSenseApi from '@/api/commonsense'
import * as languageApi from '@/api/language'
import * as quantityApi from '@/api/quantity'
import * as judgmentApi from '@/api/judgment'
import * as dataAnalysisApi from '@/api/dataAnalysis'

// 试卷数据类型定义
interface Paper {
  id?: number
  name: string
  totalDuration: number
  totalQuestions: number
  createTime?: string
  updateTime?: string
}

// 试卷表单数据
const paperForm = reactive({
  id: 0,
  name: '',
  totalDuration: 120,
  totalQuestions: 100
})

// 手动导入表单数据
const manualImportForm = reactive({
  content: ''
})

// 导入答案表单数据
const importAnswersForm = reactive({
  content: '',
  paperId: 0
})

// 搜索表单数据
const searchForm = reactive({
  name: ''
})

// 验证结果
const validationResult = reactive({
  show: false,
  valid: false,
  type: '', // 'success' 或 'error'
  title: '',
  message: '',
  details: [] as string[]
})

// 答案验证结果
const answerValidationResult = reactive({
  show: false,
  valid: false,
  type: '', // 'success' 或 'error'
  title: '',
  message: '',
  details: [] as string[]
})

// 防抖定时器
let validateTimer: number | null = null
let validateAnswersTimer: number | null = null

// 试卷表单验证规则
const paperRules = {
  name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  totalDuration: [{ required: true, message: '请输入总时长', trigger: 'blur' }],
  totalQuestions: [{ required: true, message: '请输入总题数', trigger: 'blur' }]
}

// 试卷列表
const paperList = ref<Paper[]>([])
const loading = ref(false)

// 对话框控制
const showCreatePaperDialog = ref(false)
const showManualImportDialog = ref(false)
const showImportAnswersDialogVisible = ref(false) // 添加导入答案对话框控制
const editingPaper = ref(false)
const clearingQuestions = ref(false)


// 当前试卷ID
const currentPaperId = ref(0)

// 激活的模块标签页
const activeModuleTab = ref('politics')

// 各模块题目
const paperQuestions = reactive({
  politics: [] as any[],
  commonSense: [] as any[],
  language: [] as any[],
  quantity: [] as any[],
  judgment: [] as any[],
  dataAnalysis: [] as any[]
})

// 批量删除相关状态
const showBatchDelete = ref(true) // 默认保持选择题目的状态
const selectedQuestions = reactive({
  politics: [] as number[],
  commonSense: [] as number[],
  language: [] as number[],
  quantity: [] as number[],
  judgment: [] as number[],
  dataAnalysis: [] as number[]
})

// 添加题目对话框控制状态
const showAddQuestionDialog = reactive({
  politics: false,
  commonSense: false,
  language: false,
  quantity: false,
  judgment: false,
  dataAnalysis: false
});

// 试卷分值表单数据
const paperScoreForm = reactive({
  paperId: 0,
  paperScoreId: null as number | null
});

// 试卷分值列表
const paperScoreList = ref<any[]>([]);

// 选中的试卷分值详情
const selectedPaperScore = ref<any>(null);

// 试卷分值列表加载状态
const paperScoreListLoading = ref(false);

// 试卷分值对话框控制
const showPaperScoreDialogVisible = ref(false);

// 表单引用
const paperFormRef = ref()
const router = useRouter() // 添加 router 实例

// 格式化日期时间
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取试卷列表
const fetchPaperList = async () => {
  loading.value = true
  try {
    const res: any = await paperApi.getAllPapers()
    if (res.code === 200) {
      paperList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取试卷列表失败')
    }
  } catch (error) {
    console.error('获取试卷列表失败:', error)
    ElMessage.error('获取试卷列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索试卷
const searchPapers = async () => {
  loading.value = true
  try {
    const params: any = {}
    if (searchForm.name) {
      params.name = searchForm.name
    }
    
    const res: any = await paperApi.searchPapers(params)
    if (res.code === 200) {
      paperList.value = res.data || []
    } else {
      ElMessage.error(res.message || '搜索试卷失败')
    }
  } catch (error) {
    console.error('搜索试卷失败:', error)
    ElMessage.error('搜索试卷失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  fetchPaperList()
}

// 保存试卷基本信息
const savePaperInfo = async () => {
  if (!paperFormRef.value) return
  
  await paperFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const paperData = {
          ...paperForm,
          id: paperForm.id || undefined
        }
        
        // 编辑试卷
        const res: any = await paperApi.updatePaper(paperData)
        
        if (res.code === 200) {
          ElMessage.success('试卷信息更新成功')
          fetchPaperList()
        } else {
          ElMessage.error(res.message || '试卷信息更新失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 显示试卷分值对话框
const showPaperScoreDialog = (paper: any) => {
  paperScoreForm.paperId = paper.id
  paperScoreForm.paperScoreId = null
  selectedPaperScore.value = null
  showPaperScoreDialogVisible.value = true
  loadPaperScoreList()
}

// 加载试卷分值列表
const loadPaperScoreList = async () => {
  paperScoreListLoading.value = true
  try {
    const res: any = await paperScoreApi.getPaperScores({ page: 1, size: 100 })
    if (res.code === 200 && res.data) {
      paperScoreList.value = Array.isArray(res.data.list) ? res.data.list : []
    } else {
      paperScoreList.value = []
    }
  } catch (error: any) {
    console.error('获取试卷分值列表失败:', error)
    paperScoreList.value = []
    ElMessage.error('获取试卷分值列表失败')
  } finally {
    paperScoreListLoading.value = false
  }
}

// 试卷分值选择变化
const onPaperScoreChange = (paperScoreId: number | null) => {
  if (paperScoreId) {
    const paperScore = paperScoreList.value.find(score => score.id === paperScoreId)
    selectedPaperScore.value = paperScore || null
  } else {
    selectedPaperScore.value = null
  }
}

// 应用试卷分值
const handleApplyPaperScore = async () => {
  if (!paperScoreForm.paperScoreId) {
    ElMessage.warning('请选择试卷分值配置')
    return
  }
  
  try {
    // 这里可以保存试卷与试卷分值的关联关系
    // 例如保存到数据库或sessionStorage中
    // 在实际应用中，你可能需要创建一个API来保存这种关联关系
    
    // 将试卷分值信息保存到sessionStorage，以便在测验时使用
    const selectedScore = paperScoreList.value.find(score => score.id === paperScoreForm.paperScoreId)
    if (selectedScore) {
      // 创建试卷与试卷分值的关联信息
      const paperScoreRelation = {
        paperId: paperScoreForm.paperId,
        paperScoreId: paperScoreForm.paperScoreId,
        paperScoreInfo: selectedScore
      }
      
      // 保存到sessionStorage
      sessionStorage.setItem(`paperScore_${paperScoreForm.paperId}`, JSON.stringify(paperScoreRelation))
      
      ElMessage.success('试卷分值配置应用成功')
    } else {
      ElMessage.error('未找到选中的试卷分值配置')
    }
    
    showPaperScoreDialogVisible.value = false
  } catch (error: any) {
    console.error('应用试卷分值失败:', error)
    ElMessage.error('应用试卷分值失败: ' + (error.message || '未知错误'))
  }
}

// 重置手动导入
const resetManualImport = () => {
  manualImportForm.content = '';
  validationResult.show = false;
  validationResult.valid = false;
  validationResult.type = '';
  validationResult.title = '';

  validationResult.message = '';
  validationResult.details = [];
}

// 实时格式验证（防抖）
const validateQuestionsRealTime = () => {
  // 清除之前的定时器
  if (validateTimer) {
    clearTimeout(validateTimer);
  }
  
  // 设置新的定时器，延迟500ms执行验证
  validateTimer = setTimeout(() => {
    if (!manualImportForm.content.trim()) {
      validationResult.show = false;
      validationResult.valid = false;
      return;
    }
    
    try {
      // 解析题目内容
      const questions = parseQuestions(manualImportForm.content);
      
      if (questions.length === 0) {
        validationResult.show = true;
        validationResult.valid = false;
        validationResult.type = 'error';
        validationResult.title = '验证失败';
        validationResult.message = '未解析到有效题目，请检查题目格式';
        validationResult.details = [];
        return;
      }
      
      // 验证每道题目的完整性（只验证必要字段）
      const validationDetails = [];
      let valid = true;
      
      for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        const questionNum = i + 1;
        
        if (!question.content || !question.content.trim()) {
          validationDetails.push(`第${questionNum}题：题目内容为空`);
          valid = false;
        }
        
        // 只验证选项数量，不强制要求正确答案和解析
        if (question.options && question.options.length > 0) {
          // 选择题验证
          if (question.options.length < 2) {
            validationDetails.push(`第${questionNum}题：选择题选项少于2个`);
            valid = false;
          }
          
          // 如果提供了正确答案，则验证其有效性
          if (question.correctAnswer && question.correctAnswer.trim()) {
            // 验证答案是否在选项范围内
            const validAnswers = question.options.map((opt: any, idx: number) => 
              String.fromCharCode(65 + idx)).join('');
            if (!validAnswers.includes(question.correctAnswer.toUpperCase())) {
              validationDetails.push(`第${questionNum}题：正确答案"${question.correctAnswer}"不在选项范围内`);
              valid = false;
            }
          }
        }
      }
      
      validationResult.show = true;
      validationResult.valid = valid;
      validationResult.type = valid ? 'success' : 'error';
      validationResult.title = valid ? '验证通过' : '验证失败';
      validationResult.message = valid 
        ? `格式验证通过，共解析到${questions.length}道题目` 
        : `格式验证失败，存在${validationDetails.length}个问题`;
      validationResult.details = validationDetails;
    } catch (error: any) {
      console.error('验证失败:', error);
      validationResult.show = true;
      validationResult.valid = false;
      validationResult.type = 'error';
      validationResult.title = '验证失败';
      validationResult.message = '题目格式错误，请检查后重试';
      validationResult.details = [error.message || '未知错误'];
    }
  }, 500);
}

// 实时答案格式验证（防抖）
const validateAnswersRealTime = () => {
  // 清除之前的定时器
  if (validateAnswersTimer) {
    clearTimeout(validateAnswersTimer);
  }
  
  // 设置新的定时器，延迟500ms执行验证
  validateAnswersTimer = setTimeout(() => {
    if (!importAnswersForm.content.trim()) {
      answerValidationResult.show = false;
      answerValidationResult.valid = false;
      return;
    }
    
    try {
      // 解析答案内容
      const answers = parseAnswers(importAnswersForm.content);
      
      if (answers.length === 0) {
        answerValidationResult.show = true;
        answerValidationResult.valid = false;
        answerValidationResult.type = 'error';
        answerValidationResult.title = '验证失败';
        answerValidationResult.message = '未解析到有效答案，请检查答案格式';
        answerValidationResult.details = [];
        return;
      }
      
      // 验证答案格式
      const validationDetails = [];
      let valid = true;
      
      // 检查是否有重复的题目编号
      const questionNumbers = answers.map(a => a.questionNumber);
      const duplicateNumbers = questionNumbers.filter((num, index) => questionNumbers.indexOf(num) !== index);
      if (duplicateNumbers.length > 0) {
        validationDetails.push(`存在重复的题目编号: ${[...new Set(duplicateNumbers)].join(', ')}`);
        valid = false;
      }
      
      // 检查答案是否为有效选项（A-Z）
      for (const answer of answers) {
        if (!/^[A-Z]$/.test(answer.answer)) {
          validationDetails.push(`第${answer.questionNumber}题的答案"${answer.answer}"不是有效选项`);
          valid = false;
        }
      }
      
      answerValidationResult.show = true;
      answerValidationResult.valid = valid;
      answerValidationResult.type = valid ? 'success' : 'error';
      answerValidationResult.title = valid ? '验证通过' : '验证失败';
      answerValidationResult.message = valid 
        ? `格式验证通过，共解析到${answers.length}个答案` 
        : `格式验证失败，存在${validationDetails.length}个问题`;
      answerValidationResult.details = validationDetails;
    } catch (error: any) {
      console.error('验证失败:', error);
      answerValidationResult.show = true;
      answerValidationResult.valid = false;
      answerValidationResult.type = 'error';
      answerValidationResult.title = '验证失败';
      answerValidationResult.message = '答案格式错误，请检查后重试';
      answerValidationResult.details = [error.message || '未知错误'];
    }
  }, 500);
}

// 格式验证（保留原有方法但不再使用）
const validateQuestionsFormat = () => {
  if (!manualImportForm.content.trim()) {
    validationResult.show = true;
    validationResult.valid = false;
    validationResult.type = 'error';
    validationResult.title = '验证失败';
    validationResult.message = '请输入题目内容';
    validationResult.details = [];
    return;
  }
  
  try {
    // 解析题目内容
    const questions = parseQuestions(manualImportForm.content);
    
    if (questions.length === 0) {
      validationResult.show = true;
      validationResult.valid = false;
      validationResult.type = 'error';
      validationResult.title = '验证失败';
      validationResult.message = '未解析到有效题目，请检查题目格式';
      validationResult.details = [];
      return;
    }
    
    // 验证每道题目的完整性（只验证必要字段）
    const validationDetails = [];
    let valid = true;
    
    for (let i = 0; i < questions.length; i++) {
      const question = questions[i];
      const questionNum = i + 1;
      
      if (!question.content || !question.content.trim()) {
        validationDetails.push(`第${questionNum}题：题目内容为空`);
        valid = false;
      }
      
      // 只验证选项数量，不强制要求正确答案和解析
      if (question.options && question.options.length > 0) {
        // 选择题验证
        if (question.options.length < 2) {
          validationDetails.push(`第${questionNum}题：选择题选项少于2个`);
          valid = false;
        }
        
        // 如果提供了正确答案，则验证其有效性
        if (question.correctAnswer && question.correctAnswer.trim()) {
          // 验证答案是否在选项范围内
          const validAnswers = question.options.map((opt: any, idx: number) => 
            String.fromCharCode(65 + idx)).join('');
          if (!validAnswers.includes(question.correctAnswer.toUpperCase())) {
            validationDetails.push(`第${questionNum}题：正确答案"${question.correctAnswer}"不在选项范围内`);
            valid = false;
          }
        }
      }
    }
    
    validationResult.show = true;
    validationResult.valid = valid;
    validationResult.type = valid ? 'success' : 'error';
    validationResult.title = valid ? '验证通过' : '验证失败';
    validationResult.message = valid 
      ? `格式验证通过，共解析到${questions.length}道题目` 
      : `格式验证失败，存在${validationDetails.length}个问题`;
    validationResult.details = validationDetails;
    
    if (valid) {
      ElMessage.success(`格式验证通过，共解析到${questions.length}道题目`);
    } else {
      ElMessage.error(`格式验证失败，存在${validationDetails.length}个问题`);
    }
  } catch (error: any) {
    console.error('验证失败:', error);
    validationResult.show = true;
    validationResult.valid = false;
    validationResult.type = 'error';
    validationResult.title = '验证失败';
    validationResult.message = '题目格式错误，请检查后重试';
    validationResult.details = [error.message || '未知错误'];
    ElMessage.error('题目格式错误，请检查后重试');
  }
}

// 手动批量导入题目
const handleManualImport = async () => {
  if (!manualImportForm.content.trim()) {
    ElMessage.warning('请输入题目内容');
    return;
  }
  
  try {
    // 解析题目内容
    const questions = parseQuestions(manualImportForm.content);
    
    // 清空输入框
    manualImportForm.content = '';
    showManualImportDialog.value = false;
    
    // 直接保存新导入的题目到数据库
    await saveNewQuestions(questions, activeModuleTab.value);
    
    ElMessage.success(`题目已添加到${activeModuleTab.value}模块，试卷题目保存成功，成功导入并保存 ${questions.length} 道题目`);
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('题目格式错误，请检查后重试');
  }
}

// 保存新导入的题目
const saveNewQuestions = async (newQuestions: any[], module: string) => {
  try {
    // 获取对应的API模块
    const moduleApis = {
      politics: politicsApi,
      commonSense: commonSenseApi,
      language: languageApi,
      quantity: quantityApi,
      judgment: judgmentApi,
      dataAnalysis: dataAnalysisApi
    };
    
    const api = moduleApis[module as keyof typeof moduleApis];
    
    // 先将新题目添加到本地列表中（临时状态，没有ID）
    const tempQuestions: any[] = [];
    newQuestions.forEach(question => {
      const tempQuestion = { ...question, tempId: Date.now() + Math.random() };
      paperQuestions[module as keyof typeof paperQuestions].push(tempQuestion);
      tempQuestions.push(tempQuestion);
    });
    
    // 保存新题目到对应的题目表中
    const savedQuestions = [];
    for (let i = 0; i < newQuestions.length; i++) {
      const question = newQuestions[i];
      const tempQuestion = tempQuestions[i];
      
      try {
        // 构造题目数据
        // 修复选项和正确答案的存储格式，使其保持一致
        let optionsData = '';
        if (question.options && question.options.length > 0) {
          // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
          const optionsObj: Record<string, string> = {};
          question.options.forEach((option: any, index: number) => {
            const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
            optionsObj[optionLabel] = option.content || option;
          });
          optionsData = JSON.stringify(optionsObj);
        }
        
        const questionData = {
          questionType: question.type === 'single' ? 'single_choice' : 
                       question.type === 'multiple' ? 'multiple_choice' :
                       question.type === 'trueFalse' ? 'true_false' :
                       question.type === 'fillBlank' ? 'fill_blank' : question.type,
          content: question.content,
          options: optionsData,
          correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
          explanation: question.analysis || ''
        };
        
        // 创建新题目
        const res: any = await api.addQuestion(questionData);
        if (res.code === 200) {
          // 修复：正确处理question_id字段，使用res.data.questionId
          const savedQuestion = { ...question, id: res.data.questionId || res.data.id };
          savedQuestions.push({
            module: module,
            question: savedQuestion,
            tempQuestion: tempQuestion
          });
        } else {
          ElMessage.error(`添加${module}模块题目失败: ${res.message}`);
        }
      } catch (error) {
        console.error(`保存${module}模块题目失败:`, error);
        ElMessage.error(`保存${module}模块题目失败`);
      }
    }
    
    // 构造试卷题目关联数据
    const paperQuestionsData = [];
    let order = 1;
    for (const item of savedQuestions) {
      const { module, question } = item;
      paperQuestionsData.push({
        paperId: currentPaperId.value,
        questionId: question.id,
        questionType: module,
        questionOrder: order++
      });
    }
    
    // 如果没有题目，不需要保存
    if (paperQuestionsData.length === 0) {
      ElMessage.info('没有题目需要保存');
      return;
    }
    
    // 调用API添加题目关联到数据库
    const res: any = await paperApi.addQuestionsToPaper(currentPaperId.value, paperQuestionsData);
    if (res.code === 200) {
      // 移除了单独的试卷题目保存成功提示，整合到导入成功提示中
      
      // 更新本地题目数据
      for (const item of savedQuestions) {
        const { module, question, tempQuestion } = item;
        const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
        // 查找对应的临时题目索引
        const index = moduleQuestions.findIndex((q: any) => q.tempId === tempQuestion.tempId);
        if (index !== -1) {
          // 更新题目数据，包括ID
          moduleQuestions[index] = question;
        } else {
          // 如果没找到临时题目，添加新的题目
          moduleQuestions.push(question);
        }
      }
      
      ElMessage.success(`${newQuestions.length}道题目已成功保存`);
    } else {
      ElMessage.error(res.message || '试卷题目保存失败');
      
      // 如果保存失败，移除临时添加的题目
      for (const tempQuestion of tempQuestions) {
        const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
        const index = moduleQuestions.findIndex((q: any) => q.tempId === tempQuestion.tempId);
        if (index !== -1) {
          moduleQuestions.splice(index, 1);
        }
      }
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('试卷题目保存失败');
  }
}

// 解析题目内容
const parseQuestions = (content: string) => {
  const questions = [];
  // 按题目分割（以数字开头的题目）
  const questionBlocks = content.split(/\n\d+[\uFF0E\.．]/).filter(block => block.trim());
  
  for (let i = 0; i < questionBlocks.length; i++) {
    const block = questionBlocks[i];
    if (!block.trim()) continue;
    
    let contentStr = '';
    const options: { content: string }[] = [];
    let correctAnswer = '';
    let analysis = '';
    
    // 按行分割处理
    const lines = block.split('\n');
    
    // 查找选项开始位置
    let optionStartIndex = -1;
    for (let j = 0; j < lines.length; j++) {
      const trimmedLine = lines[j].trim();
      if (trimmedLine.match(/^[A-D](\.|．)/)) {
        optionStartIndex = j;
        break;
      }
    }
    
    // 查找答案和解析位置
    let answerLineIndex = -1;
    let analysisLineIndex = -1;
    for (let j = 0; j < lines.length; j++) {
      const trimmedLine = lines[j].trim();
      if (trimmedLine.startsWith('正确答案：')) {
        answerLineIndex = j;
      } else if (trimmedLine.startsWith('解析：')) {
        analysisLineIndex = j;
      }
    }
    
    if (optionStartIndex >= 0) {
      // 有选项的题目
      contentStr = lines.slice(0, optionStartIndex).join('\n').trim();
      
      // 解析选项
      const optionsMap: Record<string, string> = {};
      for (let j = optionStartIndex; j < lines.length; j++) {
        // 遇到答案或解析行时停止
        if (j === answerLineIndex || j === analysisLineIndex) {
          break;
        }
        
        const trimmedLine = lines[j].trim();
        const optionMatch = trimmedLine.match(/^([A-D])(\.|．)\s*(.*)/);
        if (optionMatch) {
          optionsMap[optionMatch[1]] = optionMatch[3].trim();
        }
      }
      
      // 按顺序添加选项
      const optionKeys = ['A', 'B', 'C', 'D'];
      for (const key of optionKeys) {
        if (optionsMap[key]) {
          options.push({ content: optionsMap[key] });
        }
      }
    } else {
      // 没有选项的题目
      let endIndex = lines.length;
      if (answerLineIndex >= 0) {
        endIndex = answerLineIndex;
      } else if (analysisLineIndex >= 0) {
        endIndex = analysisLineIndex;
      }
      contentStr = lines.slice(0, endIndex).join('\n').trim();
    }
    
    // 提取答案
    if (answerLineIndex >= 0) {
      const answerMatch = lines[answerLineIndex].match(/正确答案：\s*([A-Da-dA-D])/);
      correctAnswer = answerMatch ? answerMatch[1].toUpperCase() : '';
    }
    
    // 提取解析
    if (analysisLineIndex >= 0) {
      analysis = lines.slice(analysisLineIndex + 1).join('\n').trim();
    }
    
    questions.push({
      content: contentStr,
      options,
      correctAnswer,
      analysis,
      type: options.length > 0 ? 'single_choice' : 'true_false'
    });
  }
  
  return questions;
}

// 保存试卷
const savePaper = async () => {
  if (!paperFormRef.value) return
  
  await paperFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res: any
        const paperData = {
          ...paperForm,
          id: paperForm.id || undefined
        }
        
        if (editingPaper.value) {
          // 编辑试卷
          res = await paperApi.updatePaper(paperData)
        } else {
          // 创建试卷
          res = await paperApi.createPaper(paperData)
        }
        
        if (res.code === 200) {
          ElMessage.success(editingPaper.value ? '试卷更新成功' : '试卷创建成功')
          showCreatePaperDialog.value = false
          fetchPaperList()
        } else {
          ElMessage.error(res.message || (editingPaper.value ? '试卷更新失败' : '试卷创建失败'))
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 显示导入答案对话框
const showImportAnswersDialog = (paper: Paper) => {
  importAnswersForm.paperId = paper.id || 0
  importAnswersForm.content = ''
  showImportAnswersDialogVisible.value = true
}

// 处理导入答案
const handleImportAnswers = async () => {
  if (!importAnswersForm.content.trim()) {
    ElMessage.warning('请输入答案内容')
    return
  }

  try {
    // 解析答案内容
    const answers = parseAnswers(importAnswersForm.content)
    
    // 调用API更新题目答案
    const successCount = await updateQuestionAnswers(answers, importAnswersForm.paperId)
    
    showImportAnswersDialogVisible.value = false
    ElMessage.success(`成功导入并更新 ${successCount} 道题目的答案`)
  } catch (error: any) {
    console.error('导入答案失败:', error)
    ElMessage.error(error.message || '导入答案失败，请检查格式是否正确')
  }
}

// 解析答案内容
const parseAnswers = (content: string) => {
  const answers: { questionNumber: number; answer: string }[] = []
  
  // 按行分割处理
  const lines = content.split('\n')
  
  for (const line of lines) {
    const trimmedLine = line.trim()
    if (!trimmedLine) continue
    
    // 匹配 "1-5: DDCCA" 格式
    const rangeMatch = trimmedLine.match(/^(\d+)-(\d+):\s*([A-Z]+)$/)
    if (rangeMatch) {
      const start = parseInt(rangeMatch[1])
      const end = parseInt(rangeMatch[2])
      const answerString = rangeMatch[3]
      
      // 验证答案数量是否匹配
      if (end - start + 1 !== answerString.length) {
        throw new Error(`第${start}-${end}行的答案数量不匹配`)
      }
      
      // 逐个添加答案
      for (let i = 0; i < answerString.length; i++) {
        const questionNumber = start + i
        const answer = answerString[i]
        answers.push({ questionNumber, answer })
      }
      continue
    }
    
    // 匹配单个题目答案格式，如 "1: A"
    const singleMatch = trimmedLine.match(/^(\d+):\s*([A-Z])$/)
    if (singleMatch) {
      const questionNumber = parseInt(singleMatch[1])
      const answer = singleMatch[2]
      answers.push({ questionNumber, answer })
    }
  }
  
  return answers
}

// 更新题目答案
const updateQuestionAnswers = async (answers: { questionNumber: number; answer: string }[], paperId: number) => {
  let successCount = 0
  
  // 获取试卷题目信息
  const res: any = await paperApi.getPaperQuestions(paperId)
  if (res.code !== 200) {
    throw new Error('获取试卷题目失败')
  }
  
  console.log('获取到的试卷题目数据:', res.data);
  
  // 创建题目编号到题目ID的映射（使用连续编号）
  const questionIdMap: Record<number, { id: number; module: string }> = {}
  
  // 收集所有模块的题目
  const allModules = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  const allQuestions: any[] = [];
  
  // 按模块顺序收集题目
  allModules.forEach(module => {
    if (res.data && res.data[module]) {
      res.data[module].forEach((question: any) => {
        allQuestions.push({
          ...question,
          module: module
        });
      });
    }
  });
  
  // 按照PaperTestPractice.vue中的逻辑为题目分配连续编号
  allQuestions.forEach((question, index) => {
    const continuousNumber = index + 1; // 连续编号从1开始
    questionIdMap[continuousNumber] = { 
      id: question.id, 
      module: question.module 
    }
    console.log(`建立映射: 连续编号${continuousNumber} -> ID${question.id} (模块: ${question.module})`);
  });
  
  console.log('题目连续编号到ID映射:', questionIdMap);
  
  // 获取各模块的API
  const moduleApis = {
    politics: politicsApi,
    commonSense: commonSenseApi,
    language: languageApi,
    quantity: quantityApi,
    judgment: judgmentApi,
    dataAnalysis: dataAnalysisApi
  }
  
  // 更新每个答案
  for (const answer of answers) {
    console.log(`处理答案: 题目编号${answer.questionNumber}, 答案${answer.answer}`);
    const questionInfo = questionIdMap[answer.questionNumber]
    if (!questionInfo) {
      console.warn(`未找到第${answer.questionNumber}题`)
      ElMessage.warning(`未找到第${answer.questionNumber}题`)
      continue
    }
    
    try {
      const api = moduleApis[questionInfo.module as keyof typeof moduleApis]
      
      // 获取题目详细信息
      const questionRes: any = await api.getQuestion(questionInfo.id.toString())
      if (questionRes.code === 200) {
        const question = questionRes.data
        
        // 更新正确答案
        const updateData = {
          ...question,
          correctAnswer: answer.answer
        }
        
        const updateRes: any = await api.updateQuestion(questionInfo.id.toString(), updateData)
        if (updateRes.code === 200) {
          successCount++
          console.log(`第${answer.questionNumber}题答案更新成功`)
        } else {
          console.error(`更新第${answer.questionNumber}题答案失败:`, updateRes.message)
          ElMessage.error(`更新第${answer.questionNumber}题答案失败: ${updateRes.message}`)
        }
      } else {
        console.error(`获取第${answer.questionNumber}题详情失败:`, questionRes.message)
        ElMessage.error(`获取第${answer.questionNumber}题详情失败: ${questionRes.message}`)
      }
    } catch (error) {
      console.error(`更新第${answer.questionNumber}题答案异常:`, error)
      ElMessage.error(`更新第${answer.questionNumber}题答案异常: ${(error as Error).message}`)
    }
  }
  
  console.log(`总共成功更新${successCount}道题目`);
  return successCount
}

// 编辑试卷
const editPaper = (paper: Paper) => {
  // 直接跳转到编辑试卷页面
  router.push(`/study-system/paper-edit/${paper.id}`);
}

// 删除试卷
const deletePaper = (paper: Paper) => {
  ElMessageBox.confirm('确定要删除该试卷吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res: any = await paperApi.deletePaper(paper.id!)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchPaperList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 获取试卷题目
const fetchPaperQuestions = async (paperId: number) => {
  try {
    console.log('开始获取试卷题目，试卷ID:', paperId);
    const res: any = await paperApi.getPaperQuestions(paperId)
    console.log('获取试卷题目返回结果:', res);
    if (res.code === 200) {
      console.log('获取到的题目数据:', res.data);
      // 移除模拟数据，使用实际返回的数据
      // 处理题目数据，确保字段名正确，并正确解析选项格式
      
      // 定义选项类型
      interface Option {
        content: string;
      }
      
      // 处理政治理论模块
      paperQuestions.politics = (res.data?.politics || []).map((question: any) => {
        console.log('政治理论题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理常识判断模块
      paperQuestions.commonSense = (res.data?.commonSense || []).map((question: any) => {
        console.log('常识判断题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理政治理论模块
      paperQuestions.politics = (res.data?.politics || []).map((question: any) => {
        console.log('政治理论题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理言语理解与表达模块
      paperQuestions.language = (res.data?.language || []).map((question: any) => {
        console.log('言语理解题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理数量关系模块
      paperQuestions.quantity = (res.data?.quantity || []).map((question: any) => {
        console.log('数量关系题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理判断推理模块
      paperQuestions.judgment = (res.data?.judgment || []).map((question: any) => {
        console.log('判断推理题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      // 处理资料分析模块
      paperQuestions.dataAnalysis = (res.data?.dataAnalysis || []).map((question: any) => {
        console.log('资料分析题目:', question);
        // 解析选项数据
        let options: Option[] = [];
        if (question.options) {
          try {
            const optionsObj = typeof question.options === 'string' ? JSON.parse(question.options) : question.options;
            if (optionsObj && typeof optionsObj === 'object') {
              // 将对象格式的选项转换为数组格式
              const optionKeys = Object.keys(optionsObj).sort();
              options = optionKeys.map(key => ({ content: optionsObj[key] }));
            }
          } catch (e) {
            // 如果解析失败，保持原样
            console.error('解析选项数据失败:', e);
          }
        }
        
        return {
          ...question,
          type: question.type || question.questionType || 'single_choice',
          options: options
        };
      });
      
      console.log('各模块题目数量:');
      console.log('政治理论:', paperQuestions.politics.length);
      console.log('常识判断:', paperQuestions.commonSense.length);
      console.log('言语理解与表达:', paperQuestions.language.length);
      console.log('数量关系:', paperQuestions.quantity.length);
      console.log('判断推理:', paperQuestions.judgment.length);
      console.log('资料分析:', paperQuestions.dataAnalysis.length);
    } else {
      ElMessage.error(res.message || '获取试卷题目失败')
    }
  } catch (error) {
    console.error('获取试卷题目失败:', error)
    ElMessage.error('获取试卷题目失败')
  }
}

// 添加题目
const addQuestion = (module: string, question: any) => {
  // 实现添加题目逻辑
  // 为新题目添加临时ID，以便后续匹配
  const questionWithTempId = { ...question, tempId: question.tempId || Date.now() + Math.random() };
  paperQuestions[module as keyof typeof paperQuestions].push(questionWithTempId);
  // 移除了单独的题目添加成功提示，整合到导入成功提示中
}

// 直接添加题目并保存到数据库
const addQuestionDirect = async (module: string, question: any) => {
  try {
    // 获取对应的API模块
    const moduleApis = {
      politics: politicsApi,
      commonSense: commonSenseApi,
      language: languageApi,
      quantity: quantityApi,
      judgment: judgmentApi,
      dataAnalysis: dataAnalysisApi
    };
    
    const api = moduleApis[module as keyof typeof moduleApis];
    
    // 构造题目数据
    let optionsData = '';
    if (question.options && question.options.length > 0) {
      // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
      const optionsObj: Record<string, string> = {};
      question.options.forEach((option: any, index: number) => {
        const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
        optionsObj[optionLabel] = option.content || option;
      });
      optionsData = JSON.stringify(optionsObj);
    }
    
    const questionData = {
      questionType: question.type === 'single' ? 'single_choice' : 
                   question.type === 'multiple' ? 'multiple_choice' :
                   question.type === 'trueFalse' ? 'true_false' :
                   question.type === 'fillBlank' ? 'fill_blank' : question.type,
      content: question.content,
      options: optionsData,
      correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
      explanation: question.analysis || ''
    };
    
    // 创建新题目
    const res: any = await api.addQuestion(questionData);
    if (res.code === 200) {
      // 获取保存后的题目ID
      const savedQuestion = { ...question, id: res.data.questionId || res.data.id };
      
      // 添加到本地列表
      paperQuestions[module as keyof typeof paperQuestions].push(savedQuestion);
      
      // 构造试卷题目关联数据
      const paperQuestionData = {
        paperId: currentPaperId.value,
        questionId: savedQuestion.id,
        questionType: module,
        questionOrder: paperQuestions[module as keyof typeof paperQuestions].length
      };
      
      // 添加题目关联到试卷
      await paperApi.addQuestionsToPaper(currentPaperId.value, [paperQuestionData]);
      
      ElMessage.success('题目添加成功');
      return savedQuestion;
    } else {
      ElMessage.error(`添加${module}模块题目失败: ${res.message}`);
      return null;
    }
  } catch (error) {
    console.error(`保存${module}模块题目失败:`, error);
    ElMessage.error(`保存${module}模块题目失败`);
    return null;
  }
}

// 直接更新题目并保存到数据库
const updateQuestionDirect = async (module: string, question: any) => {
  try {
    // 获取对应的API模块
    const moduleApis = {
      politics: politicsApi,
      commonSense: commonSenseApi,
      language: languageApi,
      quantity: quantityApi,
      judgment: judgmentApi,
      dataAnalysis: dataAnalysisApi
    };
    
    const api = moduleApis[module as keyof typeof moduleApis];
    
    // 构造题目数据
    let optionsData = '';
    if (question.options && question.options.length > 0) {
      // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
      const optionsObj: Record<string, string> = {};
      question.options.forEach((option: any, index: number) => {
        const optionLabel = String.fromCharCode(65 + index); // A, B, C, D
        optionsObj[optionLabel] = option.content || option;
      });
      optionsData = JSON.stringify(optionsObj);
    }
    
    const questionData = {
      questionType: question.type === 'single' ? 'single_choice' : 
                   question.type === 'multiple' ? 'multiple_choice' :
                   question.type === 'trueFalse' ? 'true_false' :
                   question.type === 'fillBlank' ? 'fill_blank' : question.type,
      content: question.content,
      options: optionsData,
      correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
      explanation: question.analysis || ''
    };
    
    // 更新题目
    if (question.id && typeof question.id === 'number') {
      const res: any = await api.updateQuestion(question.id.toString(), questionData);
      if (res.code === 200) {
        // 移除了重复的成功消息提示，让QuestionModule组件来显示成功消息
        // ElMessage.success(`题目已在${module}模块中更新`);
      } else {
        ElMessage.error(`更新${module}模块题目失败: ${res.message}`);
      }
    } else {
      ElMessage.error(`题目ID无效，无法更新`);
      return null;
    }
  } catch (error) {
    console.error(`更新${module}模块题目失败:`, error);
    ElMessage.error(`更新${module}模块题目失败`);
    return null;
  }
}

// 更新题目
const updateQuestion = async (module: string, question: any) => {
  // 实现更新题目逻辑
  const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
  const index = moduleQuestions.findIndex((q: any) => q.tempId === question.tempId || q.id === question.id);
  if (index !== -1) {
    moduleQuestions[index] = question;
    
    // 调用API更新题目到数据库
    try {
      // 获取对应的API模块
      const moduleApis = {
        politics: politicsApi,
        commonSense: commonSenseApi,
        language: languageApi,
        quantity: quantityApi,
        judgment: judgmentApi,
        dataAnalysis: dataAnalysisApi
      };
      
      const api = moduleApis[module as keyof typeof moduleApis];
      
      // 构造题目数据
      // 修复选项和正确答案的存储格式，使其保持一致
      let optionsData = '';
      if (question.options && question.options.length > 0) {
        // 将选项数组转换为对象格式 {A: "选项A内容", B: "选项B内容", ...}
        const optionsObj: Record<string, string> = {};
        question.options.forEach((option: any, idx: number) => {
          const optionLabel = String.fromCharCode(65 + idx); // A, B, C, D
          optionsObj[optionLabel] = option.content || option;
        });
        optionsData = JSON.stringify(optionsObj);
      }
      
      const questionData = {
        questionType: question.type === 'single' ? 'single_choice' : 
                     question.type === 'multiple' ? 'multiple_choice' :
                     question.type === 'trueFalse' ? 'true_false' :
                     question.type === 'fillBlank' ? 'fill_blank' : question.type,
        content: question.content,
        options: optionsData,
        correctAnswer: question.correctAnswer || (question.correctAnswers ? JSON.stringify(question.correctAnswers) : ''),
        explanation: question.analysis || ''
      };
      
      // 更新题目
      if (question.id && typeof question.id === 'number') {
        const res: any = await api.updateQuestion(question.id.toString(), questionData);
        if (res.code === 200) {
          // 移除了重复的成功消息提示，让QuestionModule组件来显示成功消息
          // ElMessage.success(`题目已在${module}模块中更新`);
        } else {
          ElMessage.error(`更新${module}模块题目失败: ${res.message}`);
        }
      } else {
        ElMessage.error(`题目ID无效，无法更新`);
      }
    } catch (error) {
      console.error(`更新${module}模块题目失败:`, error);
      ElMessage.error(`更新${module}模块题目失败`);
    }
  }
}

// 移除题目
const removeQuestion = async (module: string, questionId: number) => {
  // 实现移除题目逻辑
  const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
  const index = moduleQuestions.findIndex((q: any) => q.id === questionId);
  if (index !== -1) {
    // 如果题目已经有ID，直接从数据库中删除
    if (questionId && typeof questionId === 'number') {
      try {
        // 获取对应的API模块
        const moduleApis = {
          politics: politicsApi,
          commonSense: commonSenseApi,
          language: languageApi,
          quantity: quantityApi,
          judgment: judgmentApi,
          dataAnalysis: dataAnalysisApi
        };
        
        const api = moduleApis[module as keyof typeof moduleApis];
        
        // 从数据库中删除题目
        const res: any = await api.deleteQuestion(questionId.toString());
        if (res.code === 200) {
          // 从试卷中移除题目关联
          await paperApi.removeQuestionFromPaper(currentPaperId.value, questionId);
          
          // 从本地数组中移除
          moduleQuestions.splice(index, 1);
          
          ElMessage.success(`题目已从${module}模块中删除`);
        } else {
          ElMessage.error(res.message || '删除题目失败');
        }
      } catch (error: any) {
        console.error('删除题目失败:', error);
        ElMessage.error(error.message || '删除题目失败');
      }
    } else {
      // 如果题目没有ID，直接从本地数组中移除
      moduleQuestions.splice(index, 1);
      ElMessage.success(`题目已从${module}模块中移除`);
    }
  }
}

// 保存试卷题目 - 已移除，因为题目现在会直接保存
// const savePaperQuestions = async (autoSave = false) => { ... }

// 开始编辑题目
const startEditQuestions = () => {
  // 查看功能已移除
}

// 切换题目选择状态
const toggleQuestionSelection = (module: string, questionId: number, selected: boolean) => {
  const moduleSelectedQuestions = selectedQuestions[module as keyof typeof selectedQuestions];
  const index = moduleSelectedQuestions.indexOf(questionId);
  
  if (selected && index === -1) {
    // 选中题目
    moduleSelectedQuestions.push(questionId);
  } else if (!selected && index !== -1) {
    // 取消选中题目
    moduleSelectedQuestions.splice(index, 1);
  }
}

// 全选/取消全选
const toggleSelectAll = (module: string, selected: boolean) => {
  const moduleQuestions = paperQuestions[module as keyof typeof paperQuestions];
  const moduleSelectedQuestions = selectedQuestions[module as keyof typeof selectedQuestions];
  
  if (selected) {
    // 全选
    moduleQuestions.forEach(question => {
      if (!moduleSelectedQuestions.includes(question.id)) {
        moduleSelectedQuestions.push(question.id);
      }
    });
  } else {
    // 取消全选
    selectedQuestions[module as keyof typeof selectedQuestions] = [];
  }
}

// 切换批量删除模式 - 已移除，因为默认保持选择题目的状态
// const toggleBatchDeleteMode = () => { ... }

// 执行批量删除
const executeBatchDelete = async () => {
  // 收集所有选中的题目
  const allSelectedQuestions: { moduleId: number; moduleType: string }[] = [];
  
  Object.keys(selectedQuestions).forEach(module => {
    const questions = selectedQuestions[module as keyof typeof selectedQuestions];
    questions.forEach(questionId => {
      allSelectedQuestions.push({
        moduleId: questionId,
        moduleType: module
      });
    });
  });
  
  if (allSelectedQuestions.length === 0) {
    ElMessage.info('请先选择要删除的题目');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${allSelectedQuestions.length} 道题目吗？这将从题库中永久删除这些题目。`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      clearingQuestions.value = true;
      
      // 获取各模块的API
      const moduleApis = {
        politics: politicsApi,
        commonSense: commonSenseApi,
        language: languageApi,
        quantity: quantityApi,
        judgment: judgmentApi,
        dataAnalysis: dataAnalysisApi
      };
      
      // 记录删除成功的题目数量
      let successCount = 0;
      
      // 逐个删除题目
      for (const item of allSelectedQuestions) {
        try {
          const api = moduleApis[item.moduleType as keyof typeof moduleApis];
          const res: any = await api.deleteQuestion(item.moduleId.toString());
          
          if (res.code === 200) {
            successCount++;
            // 从试卷中移除题目关联
            await paperApi.removeQuestionFromPaper(currentPaperId.value, item.moduleId);
            
            // 从本地数组中移除
            const moduleQuestions = paperQuestions[item.moduleType as keyof typeof paperQuestions];
            const index = moduleQuestions.findIndex((q: any) => q.id === item.moduleId);
            if (index !== -1) {
              moduleQuestions.splice(index, 1);
            }
          } else {
            console.error(`删除${item.moduleType}模块题目失败:`, res.message);
          }
        } catch (error) {
          console.error(`删除${item.moduleType}模块题目异常:`, error);
        }
      }
      
      // 清空选中的题目
      Object.keys(selectedQuestions).forEach(key => {
        selectedQuestions[key as keyof typeof selectedQuestions] = [];
      });
      
      ElMessage.success(`成功删除 ${successCount} 道题目`);
    } catch (error) {
      console.error('批量删除题目失败:', error);
      ElMessage.error('批量删除题目失败');
    } finally {
      clearingQuestions.value = false;
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 处理添加题目按钮点击事件
const handleAddQuestion = (module: string) => {
  // 设置当前激活的模块标签页
  activeModuleTab.value = module;
  
  // 触发对应模块的添加题目对话框
  showAddQuestionDialog[module as keyof typeof showAddQuestionDialog] = true;
  
  // 在下一个tick重置状态，确保对话框能正确显示
  nextTick(() => {
    showAddQuestionDialog[module as keyof typeof showAddQuestionDialog] = false;
  });
};

// 获取模块标签文本
const getModuleLabel = (module: string) => {
  const moduleLabels: Record<string, string> = {
    politics: '政治理论',
    commonSense: '常识判断',
    language: '言语理解与表达',
    quantity: '数量关系',
    judgment: '判断推理',
    dataAnalysis: '资料分析'
  };
  return moduleLabels[module] || module;
};

// 题目更新处理
const onQuestionsUpdated = () => {
  // 只在用户明确点击保存按钮时才保存，不在题目更新时自动保存
  // 这样可以避免查看试卷时误操作
}

// 组件挂载时获取试卷列表
onMounted(() => {
  fetchPaperList()
})
</script>

<style scoped>
.paper-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-form .el-input {
  width: 300px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px; /* 添加按钮之间的间距 */
}

.dialog-footer .el-button {
  margin-left: 0; /* 重置默认的按钮左边距 */
}

.manual-import-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.validation-result {
  margin-top: 20px;
  padding: 10px;
  border-radius: 4px;
}

.validation-result.success {
  background-color: #e1f3d8;
  border: 1px solid #c2e7b0;
  color: #74be2e;
}

.validation-result.error {
  background-color: #fde2e2;
  border: 1px solid #f56c6c;
  color: #f56c6c;
}

.validation-result h4 {
  margin: 0;
  font-size: 16px;
}

.validation-result p {
  margin: 5px 0 0;
  font-size: 14px;
}

.validation-result ul {
  margin: 10px 0 0;
  padding-left: 20px;
  list-style-type: disc;
}

.validation-result li {
  margin: 5px 0;
}

.button-group {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.button-group .el-button {
  margin: 0;
  padding: 5px 10px;
  min-width: 50px;
}

.paper-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  margin: 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.paper-actions .el-button {
  margin-left: 0;
}
</style>
